<template>
  <div class="table_container">
    <el-steps :active="activeIndex-0" align-center>
      <el-step title="填写学生信息"></el-step>
      <el-step title="填写基本资料"></el-step>
      <el-step title="填写检查详情"></el-step>
    </el-steps>
    <el-form
        ref="ruleForm"
        :model="formData"
        label-width="100px"
        :rules="rules">
      <el-tabs v-model="activeIndex" tab-position="right">
        <el-divider></el-divider>
        <el-tab-pane label="学生信息" name="1">
          <div style="width: 400px; margin: 0 auto">
            <span style="font-weight: bolder;font-size: 18px;">查找学生</span>
            <br>
            <br>
            <el-form-item label="搜索查找">
              <el-select
                  style="width: 100%;"
                  @change="hendlePatient"
                  v-model="keyWord"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="输入姓名、手机、身份证"
                  :remote-method="remoteMethod"
                  :loading="loading">
                <el-option
                    v-for="(item,index) in userOptions"
                    :key="index"
                    :label="item.name + item.id_card"
                    :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-button type="text" @click="handleCreateUser">未找到用户？去新建</el-button>
            <br>
            <br>
            <el-form-item label="姓名">
              <el-input disabled v-model="formData.name"></el-input>
            </el-form-item>
            <el-form-item label="身份证号">
              <el-input disabled v-model="formData.id_card"></el-input>
            </el-form-item>
            <el-form-item label="电话">
              <el-input disabled v-model="formData.phone"></el-input>
            </el-form-item>
            <el-form-item label="年龄">
              <el-input disabled type="age" v-model.number="formData.age"></el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group disabled v-model="formData.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </el-tab-pane>
        <el-tab-pane label="基本资料" name="2">
          <div style="width: 400px; margin: 0 auto">
            <br>
            <br>
            <br>
            <el-form-item label="筛查计划" prop="batch">
              <el-select
                  style="width: 100%"
                  filterable placeholder="请选择"
                  v-model="formData.batch"
                  @change="retrieveBatch"
                  @focus="loadBatch">
                <el-option
                    v-for="item in batchOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="学段" prop="">
              <el-select
                  style="width: 100%"
                  @focus="loadStage(formData.school)"
                  v-model="formData.stage"
                  class="custorm_input"
                  filterable
                  placeholder="请选择学段">
                <el-option
                    v-for="item in stageOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="医生">
              <el-select
                  @focus="loadDoctor()"
                  v-model="formData.doctor"
                  class="custorm_input"
                  style="width: 100%"
                  filterable>
                <el-option
                    v-for="item in doctorOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择类型">
              <el-radio-group v-model="formData.report_type">
                <el-radio :label="0">初筛</el-radio>
                <el-radio :label="1">复测</el-radio>
                <el-radio :label="2">复查</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <br>
          <br>
          <br>
        </el-tab-pane>
        <el-tab-pane label="检查详情" name="3">
          <el-collapse v-model="activeNames" style="text-align: left; ">
            <el-collapse-item title="裸眼视力" name="2">
              <el-col :span="10">
                <el-form-item label="左_裸眼视力" prop="">
                  <el-input v-model="formData.OS_VASC" class="custorm_input"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="右_裸眼视力" prop="">
                  <el-input v-model="formData.OD_VASC" class="custorm_input"></el-input>
                </el-form-item>
              </el-col>
            </el-collapse-item>
            <el-collapse-item title="主观判断" name="3">
              <el-form-item label="是否近视">
                <el-switch v-model="formData.is_myopia"></el-switch>
              </el-form-item>
            </el-collapse-item>
            <el-collapse-item title="戴镜类型" name="4">
              <el-form-item label="配镜类型">
                <el-radio-group v-model="formData.glasses_type">
                  <el-radio :label="0">未配镜</el-radio>
                  <el-radio :label="1">框架镜</el-radio>
                  <el-radio :label="2">角膜塑形镜</el-radio>
                  <el-radio :label="3">其他塑形镜</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-collapse-item>
            <el-collapse-item title="矫正视力" name="5">
              <el-col :span="10">
                <el-form-item label="左_戴镜视力" prop="">
                  <el-input v-model="formData.OS_VACC" class="custorm_input"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="右_戴镜视力" prop="">
                  <el-input v-model="formData.OD_VACC" class="custorm_input"></el-input>
                </el-form-item>
              </el-col>
            </el-collapse-item>
            <el-collapse-item title="验光仪" name="6">
              <el-col :span="10">
                <el-form-item label="左_球镜" prop="">
                  <el-input v-model="formData.OS_Sph" class="custorm_input"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="右_球镜" prop="">
                  <el-input v-model="formData.OD_Sph" class="custorm_input"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="左_柱镜" prop="">
                  <el-input v-model="formData.OS_Cyl" class="custorm_input"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="右_柱镜" prop="">
                  <el-input v-model="formData.OD_Cyl" class="custorm_input"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="左_轴位" prop="">
                  <el-input v-model="formData.OS_Axis" class="custorm_input"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="右_轴位" prop="">
                  <el-input v-model="formData.OD_Axis" class="custorm_input"></el-input>
                </el-form-item>
              </el-col>
            </el-collapse-item>
            <el-collapse-item title="屈光备注" name="7">
              <el-col :span="20">
                <el-form-item label="屈光备注" prop="desc">
                  <el-input type="textarea" v-model="formData.desc" :autosize="{ minRows: 4, maxRows: 8}"></el-input>
                </el-form-item>
              </el-col>
            </el-collapse-item>
            <el-collapse-item title="眼轴AL" name="8">
              <el-col :span="10">
                <el-form-item label="左_眼轴" prop="">
                  <el-input v-model="formData.OS_AL" class="custorm_input"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="右_眼轴" prop="">
                  <el-input v-model="formData.OD_AL" class="custorm_input"></el-input>
                </el-form-item>
              </el-col>
            </el-collapse-item>
            <el-collapse-item title="眼压" name="9">
              <el-col :span="10">
                <el-form-item label="左_眼压" prop="">
                  <el-input v-model="formData.OS_IOP" class="custorm_input"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="右_眼压" prop="">
                  <el-input v-model="formData.OD_IOP" class="custorm_input"></el-input>
                </el-form-item>
              </el-col>
            </el-collapse-item>
            <el-collapse-item title="结论建议" name="10">
              <el-col :span="20">
                <el-form-item label="筛查结论">
                  <el-input type="textarea" v-model="formData.conclusion"
                            :autosize="{ minRows: 4, maxRows: 8}"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="20">
                <el-form-item label="处理建议">
                  <el-input type="textarea" v-model="formData.suggest" :autosize="{ minRows: 4, maxRows: 8}"></el-input>
                </el-form-item>
              </el-col>
            </el-collapse-item>
            <el-collapse-item title="其他情况" name="11">
              <el-col :span="20">
                <el-form-item label="其他情况">
                  <el-input type="textarea" v-model="formData.other" :autosize="{ minRows: 4, maxRows: 8}"></el-input>
                </el-form-item>
              </el-col>
            </el-collapse-item>
          </el-collapse>
          <el-col :span="24">
            <el-divider></el-divider>
            <el-form-item style="text-align: right">
              <el-button @click="addDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click='onSubmit("ruleForm")'>提 交</el-button>
            </el-form-item>
          </el-col>
        </el-tab-pane>
      </el-tabs>
      <el-divider></el-divider>
      <div style="margin-bottom: 50px;">
        <el-button-group class="btnRight">
          <el-button
              :disabled="previousDisabled"
              @click="previous"
              type="primary" plain
              icon="el-icon-arrow-left">
            上一页
          </el-button>
          <el-button :disabled="nextDisabled" @click="next" type="primary" plain>
            下一页<i class="el-icon-arrow-right el-icon--right"></i>
          </el-button>
        </el-button-group>
      </div>
    </el-form>

    <el-dialog title="新建患者" width="400px" @close="handleClose" :visible.sync="createDialogFormVisible">
      <el-form :model="form" style="text-align: left" label-width="80px" :rules="rulesUser">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card">
          <el-input v-model="form.id_card"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model.number="form.phone"></el-input>
        </el-form-item>

        <el-form-item label="生日">
          <el-date-picker
              style="width: 100%"
              v-model="form.birth"
              type="date"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="父母姓名">
          <el-input v-model="form.parent_name"></el-input>
        </el-form-item>
        <el-form-item label="父母电话">
          <el-input v-model.number="form.parent_phone"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCreatePatient">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>


import {createPatient, createReport, getBatchAll, getBatchById, getDoctor, getPatient, getPatientAll} from "@/api";

export default {
  name: "createReport",
  data() {
    let validateIdCard = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入身份证号'));
      } else {
        checkArchiveUserInfo({idCard: value}).then(response => {
          callback();
        }).catch(error => {
          callback(new Error('身份证号已存在！'));
        })
      }
    };
    return {
      previousDisabled: true,
      nextDisabled: false,
      activeIndex: '1',
      userOptions: [],
      stageOptions: [],
      gradeOptions: [],
      //可选框相关
      batchOptions: [],
      hospitalOptions: [],
      schoolOptions: [],
      countryOptions: [],
      regionOptions: [],
      doctorOptions: [],

      formData: {
        OD_AL: undefined,
        OD_Axis: undefined,
        OD_Cyl: undefined,
        OD_IOP: undefined,
        OD_PD: undefined,
        OD_SE: undefined,
        OD_Sph: undefined,
        OD_VACC: undefined,
        OD_VASC: undefined,
        OS_AL: undefined,
        OS_Axis: undefined,
        OS_Cyl: undefined,
        OS_IOP: undefined,
        OS_PD: undefined,
        OS_SE: undefined,
        OS_Sph: undefined,
        OS_VACC: undefined,
        OS_VASC: undefined,
        age: undefined,
        batch: undefined,
        conclusion: undefined,
        creator: undefined,
        desc: undefined,
        doctor: undefined,
        gender: undefined,
        glasses_type: 0,
        grade: undefined,
        is_myopia: 0,
        other: undefined,
        stage: undefined,
        suggest: undefined,
        patient: undefined,
        report_type: 0
      },
      temBatch: {
        hospital_name: '',
        school_name: '',
        semester: '',
      },

      rules: {
        id_card: [
          {validator: validateIdCard, trigger: 'blur'}
        ],
      },
      loading: true,
      keyWord: '',
      dialogVisible: false,

      //  折叠面板默认展开
      activeNames: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'],
      //当前选中的部门id
      deptId: undefined,

      createDialogFormVisible: false,
      form: {
        name: undefined,
        id_card: undefined,
        gender: 0,
        birth: undefined,
        phone: undefined,
        parent_name: undefined,
        parent_phone: undefined,
        status: true
      },
      // 表单校验
      rulesUser: {
        name: [
          {required: true, message: '姓名不能为空', trigger: 'blur'}
        ],
        id_card: [
          {required: true, message: '身份证号不能为空', trigger: 'blur'},
          {validator: this.validID, trigger: 'blur'}
        ]
      },

    }
  },
  watch: {
    activeIndex(newValue, oldValue) {
      this.previousDisabled = newValue === '1'
      this.nextDisabled = newValue === '3'
    },
  },
  methods: {
    previous() {
      if (--this.activeIndex < 1) {
        this.activeIndex = '3'
      } else {
        this.activeIndex = this.activeIndex.toString()
      }
    },
    next() {
      if (++this.activeIndex > 3) {
        this.activeIndex = '1';
      } else {
        this.activeIndex = this.activeIndex.toString()
      }
    },
    //远程获取患者列表
    remoteMethod(keyWord) {
      if (keyWord !== '') {
        this.loading = true;
        getPatientAll({keyWord: keyWord}).then(response => {
          // response.data.forEach(item => {
          //   this.userOptions.push({
          //     label: item.name + item.id_card,
          //     value: item
          //   });
          // })
          this.userOptions = response.data
          this.loading = false;
        })
      } else {
        this.userOptions = [];
      }
    },
    // 选定患者后
    hendlePatient(data) {
      this.keyWord = data.name + data.id_card
      // console.log(data)
      this.formData.patient = data.id
      this.formData.name = data.name
      this.formData.gender = data.gender
      this.formData.id_card = data.id_card
      this.formData.phone = data.phone
      this.formData.birth = data.birth
      this.formData.age = this.getAge(data.birth)
    },
    // 自动计算年龄
    getAge(val) {
      let currentYear = new Date().getFullYear() //当前的年份
      let calculationYear = new Date(val).getFullYear() //计算的年份
      const wholeTime = currentYear + val.substring(4) //周岁时间
      const calculationAge = currentYear - calculationYear //按照年份计算的年龄
      //判断是否过了生日
      if (new Date().getTime() > new Date(wholeTime).getTime()) {
        return calculationAge
      } else {
        return calculationAge - 1
      }
    },
    //自动加载批号列表
    loadBatch() {
      this.batchOptions = []
      getBatchAll().then(res => {
        res.data.forEach(item => {
          this.batchOptions.push({
            label: `${item.school_label}（${item.number}）${item.hospital_label}`,
            value: item.id
          })
        })
      })
    },
    //选定batch后自动给全局变量定义部门id
    retrieveBatch() {
      getBatchById(this.formData.batch).then(res => {
        this.deptId = res.data.hospital
      })
    },
    //自动加载医生列表
    loadDoctor() {
      this.doctorOptions = []
      // 获取到部门 id 然后在用户表中检索匹配的医生
      getDoctor({deptId: this.deptId}).then(res => {
        res.data.forEach(item => {
          this.doctorOptions.push({
            label: `${item.name}(${item.dept_info.name})`,
            value: item.id,
          })
        })
      })

    },
    // 自动加载学段可选项
    loadStage(schoolId) {
      this.stageOptions = [
        {label: "幼儿园", value: "幼儿园"},
        {label: "小学", value: "小学"},
        {label: "初中", value: "初中"},
        {label: "高中", value: "高中"},
        {label: "其他", value: "其他"},
      ]
    },
    handleClose() {
      this.form = {
        name: undefined,
        id_card: undefined,
        gender: 0,
        birth: undefined,
        phone: undefined,
        parent_name: undefined,
        parent_phone: undefined,
        status: true
      }
    },
    submitCreatePatient() {
      let data = this.form
      createPatient(data).then(res => {
        this.$message.success('新建成功！')
        this.createDialogFormVisible = false
        this.hendlePatient(res.data)
      })
    },
    // 身份证验证
    async validID(rule, value, callback) {
      // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
      let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (reg.test(value)) {
        await this.go(value.length);
        callback()
      } else {
        callback(new Error('身份证号码不正确'))
      }
    },
    // 实现自动生成生日，性别，年龄
    go(val) {
      let iden = this.form.id_card;
      let sex = null;
      let birth = null;
      let myDate = new Date();
      let month = myDate.getMonth() + 1;
      let day = myDate.getDate();
      let age = 0;

      if (val === 18) {
        age = myDate.getFullYear() - iden.substring(6, 10) - 1;
        sex = iden.substring(16, 17);
        birth = iden.substring(6, 10) + "-" + iden.substring(10, 12) + "-" + iden.substring(12, 14);
        if (iden.substring(10, 12) < month || iden.substring(10, 12) === month && iden.substring(12, 14) <= day) age++;

      }
      if (val === 15) {
        age = myDate.getFullYear() - iden.substring(6, 8) - 1901;
        sex = iden.substring(13, 14);
        birth = "19" + iden.substring(6, 8) + "-" + iden.substring(8, 10) + "-" + iden.substring(10, 12);
        if (iden.substring(8, 10) < month || iden.substring(8, 10) === month && iden.substring(10, 12) <= day) age++;
      }

      if (sex % 2 === 0)
        sex = 2;
      else
        sex = 1;
      //性别  ==> 1:男       2:女
      this.form.age = age;
      this.form.gender = sex;
      this.form.birth = birth;
    },

    //显示创建用户对话框
    handleCreateUser() {
      this.createDialogFormVisible = true
    },
    // 自动加载年级可选项
    async loadGrade(stageId) {
      this.gradeOptions = []
      let result = await getGrade({stageId: stageId})
      result.data.forEach(
          grade => {
            this.gradeOptions.push({
              value: grade.name,
              label: grade.name,
            })
          }
      )
    },
    //表单提交
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = this.formData
          createReport(data).then(response => {
            this.$message.success('新建成功')
            this.$router.back()
          })
        }
      })
    },


  }
}
</script>

<style scoped>
.table_container {
  padding: 30px;
  background: #fff;
  border-radius: 2px;
}

.btnRight {
  float: right;
  margin-right: 100px !important;
}

.user-info-input {
  width: 300px;
}
</style>
